package com.glsc.ngateway.opmanage.service.report.excel.listener.regulatory;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.fileupload.ImportTemplateRulesDefine;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.regulatory.RegRptNAFMIIIRS;
import com.glsc.ngateway.common.base.dto.opmanage.report.DerivativeException;
import com.glsc.ngateway.common.base.repo.mysql.opmanage.report.regulatory.RegRptNAFMIIIRSRepo;
import com.glsc.ngateway.opmanage.service.report.excel.listener.TemplateCheckHandler;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RegRptNAFMIIIRSListener extends AnalysisEventListener<RegRptNAFMIIIRS> {
    Logger logger = LoggerFactory.getLogger(RegRptNAFMIIIRSListener.class);

    private static final int BATCH_COUNT = 3000;
    List<RegRptNAFMIIIRS> list = new ArrayList<RegRptNAFMIIIRS>();

    private List<ImportTemplateRulesDefine> rulesDefineList;
    private RegRptNAFMIIIRSRepo tnafmiiirsRepo;
    private BigInteger mainId;
    private BigInteger id;

    public RegRptNAFMIIIRSListener() {
    }

    public RegRptNAFMIIIRSListener(RegRptNAFMIIIRSRepo tnafmiiirsRepo, BigInteger mainId,
                                   List<ImportTemplateRulesDefine> rulesDefineList) {
        this.tnafmiiirsRepo = tnafmiiirsRepo;
        this.mainId = mainId;
        this.id = BigInteger.valueOf(1);
        this.rulesDefineList = rulesDefineList.stream().filter(item -> item.getSheetIndex().equals(1)).collect(Collectors.toList());
    }

    @SneakyThrows
    @Override
    public void invoke(RegRptNAFMIIIRS data, AnalysisContext analysisContext) {
        if (data.getDate() != null) {
            data.setId(id);
            data.setMainId(mainId);
            list.add(data);
            id = id.add(BigInteger.valueOf(1));
        }

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        logger.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            logger.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        } else if (exception instanceof DerivativeException) {
            throw exception;
        }
    }

    //读取表头内容
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        TemplateCheckHandler.check(context, rulesDefineList);
        System.out.println("表头：" + headMap);
    }

    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        tnafmiiirsRepo.saveAll(list);
    }
}
